from pyquery.pyquery import PyQuery
from core.base_spider import *
from core.item import *


class Spider(BookSpider):
    def __init__(self,request=None, logger=None, *args, **kwargs) -> None:
        super().__init__(request=request, logger=logger, *args, **kwargs)
        self.base_url='https://cn.baozimh.com'
        self.search_url='https://cn.baozimh.com/search?q='

    def parse_book(self,selector:PyQuery):
        title=selector('.comics-detail__title').text()
        if not title:
            raise ParseBookException('Parse book title failed!')
        self.logger.info(f'Find book title:{title}')
        cover_url=selector('.l-content>div>div>amp-img')[0].attrib.get('src')
        self.logger.info(f'Find book cover url:{cover_url}')

        selector.make_links_absolute(self.base_url)
        chapter_links=selector('#chapter-items>div>a,#chapters_other_list>div>a')
        if not chapter_links:
            raise ParseBookException('Parse chatper url list failed!')
        chapter_count=len(chapter_links)
        self.logger.info(f'find chapter count:{chapter_count}')
        chapter_urls=[]
        for link in chapter_links:     
            url=link.attrib.get('href',None)
            if not url:
                self.logger.warn('Empty chapter url.')
                continue
            chapter_urls.append(url)

        if len(chapter_urls)!=chapter_count:
            self.logger.warn(f'The number[{len(chapter_urls)}] of parsed chapters do not math for the target number[{chapter_count}]!')
        return (title,cover_url,chapter_urls)


    
    def parse_chapter(self,selector:PyQuery):
        title=selector('.header span.title').text()
        if not title:
            raise ParseBookException('Parse chapter title failed!')
        logger.info(f'find chapter title:{title}')
        imgs=selector('.chapter-main amp-img')
        if not imgs:
            raise ParseBookException('Parse image url list failed!')
        page_count=len(imgs)
        self.logger.info(f'Find pages count:{page_count}')
        pages=[]
        for img in imgs:
            page_url=img.attrib.get('src',None)
            if not page_url:
                continue
            pages.append(page_url)
        if len(pages)!=page_count:
            logger.warn(f'The number[{len(pages)}] of parsed pages do not math for the target number[{page_count}]!')
        return (title,pages)

    def parse_search(self,selector:PyQuery,result_count):
        links=selector('div.comics-card>.comics-card__poster')[:result_count]
        book_url_list=[]
        for link in links:
            part_url=link.attrib.get('href')
            if not part_url:
                self.logger.warn('Empty book url in search page.')
                continue
            book_url_list.append(self.join_url(part_url))
        return book_url_list
            
            

if __name__ == '__main__':
    pass